package com.xf.system.utils.excel;

import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

/**
 * @Author xiefengf
 * Excel中单元格处理器，用于自定义单元格样式
 */
public class ExcelCellHandler implements CellWriteHandler {

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        // 判断是否是表头
//        Boolean head = context.getHead();
        // 单元格内容
        Cell cell = context.getCell();
        //获取第几列，从0开始
        int columnIndex = cell.getColumnIndex();
        // 获取单元格内容
        String cellValue = context.getCell().getStringCellValue();
        // 获取格式
        Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
        // 设置格式字体颜色
        Font font = workbook.createFont();
        font.setColor(Font.COLOR_RED);
        // 获取富文本内容
        XSSFRichTextString richTextString = new XSSFRichTextString(cell.getStringCellValue());

        // 按索引填充颜色
        if(columnIndex == 0){
            richTextString.applyFont(3,4,font);
        }
        // 按文本内容填充颜色
        if ("测试".equals(cellValue)){
            richTextString.applyFont(3,4,font);
        }

        //应用配置
        cell.setCellValue(richTextString);
    }
}
